package com.regretbuying.front.service.shopping_cart.impl;

import com.regretbuying.front.dao.shopping_cart.CartDao;
import com.regretbuying.front.service.shopping_cart.CartService;
import com.regretbuying.pojo.Cart;
import com.regretbuying.pojo.Coupons;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("fcasi")
public class CartServiceImpl implements CartService {

    @Autowired
    private CartDao cartDao;


    @Override
    public Coupons getCouponsById(String id) {
        return cartDao.getCouponsById(id);
    }

    @Override
    public boolean addCar(Cart cart) {
        boolean result = false ;
        Map map = new HashMap();

        //1、先判断要添加的商品在购物车里有没有被添加过
        int count = cartDao.selectCountById(cart.getMemberId(),cart.getGoodsId(),cart.getSpecsId()) ;

        //2、判断count==0，说明一次也没有添加过，直接加入到表里即可，count==1则修改数量
        if(count == 0) {
            int insertCount = cartDao.insertCart(cart) ;
            result = true ;
        }else {
            map.put("mid",cart.getMemberId());
            map.put("gid",cart.getGoodsId());
            map.put("sid",cart.getSpecsId());
            map.put("amount",cart.getCartNumber());

            int updateCount = cartDao.updateAmount(map) ;
            result = true ;
        }

        return result;
    }

    @Override
    public int getGoodsCount(int id) {
        if(cartDao.GoodsCount(id) <= 0 ){
            return 0;
        }
        return cartDao.GoodsCount(id);
    }

    @Override
    public double CountUnitPrice(int id) {
        if(cartDao.getCartMemberById(id) == null ){
            return 0.0;
        }

        double sum = 0;

        List<Cart> cartList = cartDao.getCartMemberById(id);

        for(Cart cart : cartList){
            sum += cart.getUnitPrice()*cart.getCartNumber();
        }

        return sum;
    }

    @Override
    public List<Cart> getCartMemberById(int id) {
        return cartDao.getCartMemberById(id);
    }

    @Override
    @Transactional
    public boolean updateCart(int cartId, int cartNumber) {
        boolean result = false ;

        if(cartDao.updateCart(cartId, cartNumber) == 1) {
            result = true ;
        }
        return result;
    }

    @Override
    @Transactional
    public boolean daleteCart(int[] id) {
        boolean result = false ;

        if(cartDao.deleteCart(id) >= 1) {
            result = true ;
        }
        return result;
    }
}
